<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="robot_name"
            placeholder="请输入机器人名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px" @change="getRobotName($event)"
          />
        </div>
        <div class="head-container" style="border:1px solid #0a328a;">
          <!--机器人列表-->
          <el-table v-loading="false" :data="robotList1" @row-click="getSelectdata" @selection-change="handleSelectionChange" :cell-style="{borderColor:'rgb(1 5 43)'}" :header-cell-style="{borderColor: 'rgb(1 5 43)'}">
            <el-table-column label="机器人编号" align="center" prop="robot_num"/>
            <el-table-column label="机器人名称" align="center" prop="robot_name"  width="90px"/>
          </el-table>
        </div>
      </el-col>
    <!--查询条件区域-->
    <el-col :span="20" :xs="24">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="PLC IP" prop="plc_ip">
        <el-input
          v-model="queryParams.plc_ip"
          placeholder="请输入PLC IP"
          clearable
          @keyup.enter.native="handleQuery"
          size="small"
        />
      </el-form-item>
      <el-form-item label="PLC端口" prop="plc_port">
        <el-input
          v-model="queryParams.plc_port"
          placeholder="请输入plc端口"
          clearable
          @keyup.enter.native="handleQuery"
          size="small"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
     <!--增删改查按钮区域-->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['robot:plc:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['robot:plc:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['robot:plc:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
     <!-- 数据列表区域-->
    <el-table v-loading="loading" :data="plcList" @selection-change="handleSelectionChange" :cell-style="{borderColor:'rgb(1 5 43)'}" :header-cell-style="{borderColor: 'rgb(1 5 43)'}">
      <el-table-column type="selection" width="55" align="center" />
     <!-- <el-table-column label="序号" type="index" align="center" prop="id"/> -->
      <el-table-column label="状态" align="center" prop="robot_state" width="120px">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.plc_state==1" style="font-size: 12px!important;height: 26px!important;line-height: 26px!important;width: 40px!important;display:inline-block!important;border-radius:4px!important;background: #20c013!important;border: 1px solid #024697!important;color: #fff!important;" >在线</el-tag>
          <span v-else style="font-size: 12px!important;height: 26px!important;line-height: 26px!important;width: 40px!important;display:inline-block!important;border-radius:4px!important;background:#6c6b6b!important;border: 1px solid #024697!important;color: #fff!important;">离线</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="PLC柜名称" align="center" prop="plc_name" width="140" />
      <el-table-column label="机器人名称" align="center" prop="robot_name"/>-->
      <el-table-column label="PLC柜名称" align="center" prop="plc_name" width="180px">
        <template slot-scope="scope">
          <span>{{scope.row.plc_name}}_{{scope.row.robot_name}}</span>
        </template>
      </el-table-column>

      <el-table-column label="PLC柜号" align="center" prop="plc_num" width="80px">
        <template slot-scope="scope">
          <el-tag>{{scope.row.plc_num}}号</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="PLC IP"
        align="center"
        prop="plc_ip"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="PLC端口" align="center" prop="plc_port"/>
      <el-table-column label="创建时间" align="center" prop="creater_time"  width="200" >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.creater_time) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width"  width="200px">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-zoom-out"
            @click="handleclosed(scope.row)"
            v-hasPermi="['robot:conn:colseplcconn']"
          >断开</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-zoom-in"
            @click="handleopen(scope.row)"
            v-hasPermi="['robot:conn:connplc']"
          >连接</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['robot:plc:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['robot:plc:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--列表分页区域-->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList" style="background:rgb(1 5 43);"
    />
    </el-col>
    </el-row>
    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" @close="handleCancle" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
<!--        <el-col :span="12">
          <el-form-item label="站点名称" prop="site_id">
            <el-select v-model="form.site_id" placeholder="请选择站点名称"  clearable @change="getOptions">
              <el-option
                v-for="item in siteList"
                :key="item.id"
                :label="item.site_name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>-->
        <el-col :span="12">
          <el-form-item label="工艺名称" prop="process_body_id">
            <el-select v-model="form.process_body_id" clearable  placeholder="请选择工艺名称" @change="getOptionsgyt">
              <el-option
                v-for="item in processbodyList"
                :key="item.id"
                :label="item.process_name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="机器人" prop="robot_config_id">
              <el-select v-model="form.robot_config_id" clearable  placeholder="请选择机器人" @change="getOptionsjqr">
                <el-option
                  v-for="item in robotList"
                  :key="item.id"
                  :label="item.robot_name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="PLC IP" prop="plc_ip">
            <el-input v-model="form.plc_ip" placeholder="请输入PLCIP" />
          </el-form-item>
        </el-col>
          <el-col :span="12">
            <el-form-item label="PLC端口" prop="plc_port">
              <el-input v-model="form.plc_port" placeholder="请输入PLC端口" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="PLC名称" prop="plc_name">
              <el-input v-model="form.plc_name" placeholder="请输入PLC名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="PLC柜号" prop="plc_num">
              <el-select v-model="form.plc_num" placeholder="请选择PLC柜号" clearable>
                <el-option
                  v-for="item in plcnum"
                  :key="item.plc_num"
                  :label="item.plc_num_name"
                  :value="item.plc_num"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <span style="color: #C03639;font-size: 12px">注意！PLC柜号：1号柜比2、3号柜操作更多。若只有一个plc柜选“1号柜”以此类推。</span>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容(0-255)"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" id="plcglid" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import $ from 'jquery';
import {addPlc, delPlc, getPlc, listPlc, listsPlc, updatePlc} from "@/api/robot/plc/plc";
import {listSite} from "@/api/robot/site/site";
import {listProcessBody} from "@/api/robot/processbody/processbody";
import {listonPageRobotConfig, listRobotConfig} from "@/api/robot/robotconfig/robotconfig";
import {plcconnCmd, plclosedCmd} from "@/api/robot/modbus/modbus";
import "@/assets/styles/robt-bg.css";

export default {
  data() {
    return {
      selectedArrData: [], // 把选择到的当前行的id存到数组中
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      plc_names:[],
      timer:null,//定时器
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      robot_name: undefined,
      //机器人列表
      robotList:[],
      robotList1:[],
      //工艺体表格数据
      processbodyList:[],
      // 添加或修改对话框---站点表格数据
      siteList: [],
      // plc表格数据
      plcList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      queryparm:{
        plcid:undefined,
        plcip:undefined,
        plcport:undefined
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 8,
        plc_ip: undefined,
        plc_port: undefined
      },
      //plc柜号
      plcnum: [
        {plc_num:1,plc_num_name:"1号柜"},
        {plc_num:2,plc_num_name:"2号柜"},
        {plc_num:3,plc_num_name:"3号柜"}
      ],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        plc_ip: [
          { required: true, message:"PLCIP不能为空", trigger: "blur" }
        ] ,
        plc_port: [
          { required: true, message: "PLC端口不能为空", trigger: "blur" }
        ] ,
        process_body_id: [
          { required: true, message: "工艺名称不能为空"}
        ],
        robot_config_id: [
          { required: true, message: "机器人名称不能为空"}
        ],
        plc_name: [
          { required: true, message: "plc名称不能为空", trigger: "blur" }
        ],
        plc_num: [
          { required: true, message: "plc柜号不能为空"}
        ]
      }
    };
  },
  created() {
    //页面初始化执行方法
    this.getList();
    this.getrobotList();//机器人列表
  },
  mounted() {
    this.timer = setInterval(()=>{
      this.getList();//刷新站点列表
      console.log("plc在线离线定时器")
    },6000);//6秒
  },
  beforeDestroy() {
    //清除定时器
    if(this.timer) {
      clearInterval(this.timer); //关闭
    }
  },
  methods: {
    //获取当前选中机器人数据
    getSelectdata(row){
      this.queryParams.robot_config_id = row.id;
      this.getList();
    },
    /** 根据输入框机器人名称，查询机器人列表 */
    getRobotName(robot_name){
      this.queryParams.robot_name = robot_name;
      this.getrobotList();
    },
    /** 查询机器人列表 */
    getrobotList() {
      this.loading = false;
      listonPageRobotConfig(this.queryParams).then(response => {
        this.robotList1 = response.rows;
      });
    } ,
    //自定义对话框关闭方法
    handleCancle () {
      $("#plcglid").css("display","");
      this.queryParams.robot_config_id = null;
      this.queryParams.robot_name = null;
      this.processbodyList=[],//工艺列表
      this.robotList=[],//机器人列表
      this.$refs.form.resetFields()
      this.dialogVisible = false
    },
    //强制plc断网
    handleclosed(row){
      //this.queryparm.plcid = row.plcid;
      this.queryparm.plcid = row.robot_config_id+"_"+row.plc_num;
      this.queryparm.plcport = row.plc_port;
      plclosedCmd(this.queryparm).then(response => {
        if(typeof(response) != null && response != ""&& response.msg!=""){
          this.$modal.msg(response.msg);
        }
      });
    },
    //强制plc打开
    handleopen(row){
      //this.queryparm.plcid = row.plcid;
      this.queryparm.plcid = row.robot_config_id+"_"+row.plc_num;
      this.queryparm.plcip = row.plc_ip;
      this.queryparm.plcport = row.plc_port;
      //打开jqr连接
      plcconnCmd(this.queryparm).then(response => {
        if(typeof(response) != null && response != ""&& response.msg!=""){
          this.$modal.msg(response.msg);
        }
      });
    },
    /*工艺体查询机器人列表*/
    getOptionsgyt(id){
       /** 查询机器人列表 */
       this.queryParams.robot_name = null;
       this.queryParams.process_body_id = id;//设置站点id条件，查询工艺体
       listRobotConfig(this.queryParams).then(response => {
          this.queryParams.process_body_id = undefined;
          this.robotList = response.rows;
       });
    },
    //根据jqr的id查询plc柜子，大于2不添加。
    getOptionsjqr(id){
      this.queryparm.robot_config_id = id;
      listsPlc(this.queryparm).then(response => {
        if(typeof response!="undefined" && response!= null && response.rows.length > 3){
          $("#plcglid").css("display","none");
          this.$modal.confirm1('当前机器人，最多关联3个plc柜！');
        } else {
          $("#plcglid").css("display","");
        }
      });
      this.queryParams.robot_config_id = undefined;
    },
    getOptions(id){
      this.queryParams.site_id = id;//设置站点id条件，查询工艺体
      /** 查询工艺体列表 */
      listProcessBody(this.queryParams).then(response => {
        this.processbodyList=[];
        this.processbodyList = response.rows;
        this.queryParams.site_id = undefined;
      });
    },
    /** 添加或修改对话框--查询站点列表 */
    getsiteList() {
      listSite(this.queryParams).then(response => {
        this.siteList = response.rows;
      });
    },
    /** 查询plc列表 */
    getList() {
      this.loading = true;
      listPlc(this.queryParams).then(response => {
        this.plcList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        creater_id:undefined,
        creater_time:undefined,
        remark: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.robot_config_id=null;
      this.queryParams.robot_name = null;
      this.queryParams.plc_ip=null;
      this.queryParams.plc_port=null;
      this.queryParams.site_id=null;
      this.queryParams.process_body_id=null;
      this.queryParams.id=null;
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.plc_names = selection.map(item => item.plc_name)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增PLC";
      this.getOptions();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getPlc(id).then(response => {
        //反显的时候用，手动调用 start
        this.getOptions(response.data.site_id);
        this.getOptionsgyt(response.data.process_body_id);
        //end
        this.form = response.data;
        this.open = true;
        this.title = "修改PLC";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updatePlc(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPlc(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
         //重置参数值
          this.queryParams.pld_ip=null;
          this.queryParams.plc_port=null;
          this.queryParams.site_id=null;
          this.queryParams.process_body_id=null;
          this.queryParams.id=null;
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      const plc_names =row.plc_name || this.plc_names
      this.$modal.confirm('是否确认删除PLC柜名称为"' + plc_names + '"的数据项？').then(function() {
      // this.$modal.confirm('是否确认删除选中的数据项？').then(function() {
        return delPlc(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    }
  }
};
</script>
